package com.egao.common.module.system.transfer;

import com.egao.common.core.web.JsonResult;
import com.egao.common.module.cms.entity.Link;
import com.egao.common.module.cms.service.LinkService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;

/**
 * 链接数据导入
 *
 * @author pyx
 */
@Api(tags = "链接数据迁移")
@RestController
@Slf4j
public class LinkDataController {
    @Value("${old.datasource.jyurl}")
    private String url;

    @Value("${old.datasource.username}")
    private String userName;

    @Value("${old.datasource.password}")
    private String password;

    @Autowired
    private LinkService linkService;

    public JsonResult link() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
            st = conn.createStatement();
            String sql = "SELECT * FROM link WHERE del_flag = '0'";
            rs = st.executeQuery(sql);

            while (rs.next()) {
                Link link = new Link();
                link.setOldId(rs.getString("ID"));
                link.setSort(rs.getInt("Sort"));
                link.setImgUrl(rs.getString("PicUrl"));
                link.setLinkUrl(rs.getString("WebUrl"));
                link.setTitle(rs.getString("Title"));
                link.setCreateTime(rs.getDate("create_date"));
                link.setUpdateTime(rs.getDate("update_date"));
                int linkType = rs.getInt("LinkType");
                String type = null;
                if(linkType == 6){
                    type = "2";
                }
                if(linkType == 1 || linkType == 3){
                    type = "1";
                }
                link.setType(type);

                try {
                    linkService.save(link);
                }catch (Exception e){
                    log.error("插入id为: {} 的数据出现异常",rs.getString("id"));
                    break;
                }

            }
        }catch (ClassNotFoundException | SQLException e){
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                st.close();
                conn.close();
                return JsonResult.ok();
            }catch (SQLException e){
                e.printStackTrace();
                return JsonResult.error();
            }
        }
    }
}
